package org.easy.sse;

import org.easy.sse.dto.EventSourceWriteEventCallback;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;

import java.util.concurrent.CountDownLatch;


@Slf4j
public class EventSourceCallbackListener extends EventSourceListener {

    private final CountDownLatch latch;

    private final EventSourceWriteEventCallback callback;


    public EventSourceCallbackListener(EventSourceWriteEventCallback client, CountDownLatch latch) {
        super();
        this.latch = latch;
        this.callback = client;
    }

    @Override
    public void onOpen(EventSource eventSource, Response response) {
        super.onOpen(eventSource, response);
        callback.onOpen();
    }


    @Override
    public void onEvent(EventSource eventSource, String id, String type, String allData) {
        callback.onEvent(allData);
    }

    @Override
    public void onFailure(EventSource eventSource, Throwable t, Response response) {
        log.error("EventSourceCallbackListener onFailure ");
        latch.countDown();
    }

    @Override
    public void onClosed(EventSource eventSource) {
        super.onClosed(eventSource);
        latch.countDown();
    }


}
